package controller;

import entity.User;
import util.DBManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class UserController {
    public static void main(String[] args) throws Exception {
        CreateList();
        premenu();
    }

    /**chuangjian*/
    public static List<User> CreateList() throws Exception{
        Connection conn = DBManager.getconn();
        String sql = "select * from user";
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        List<User> userList = new ArrayList<>();
        while (rs.next()){
            User user = new User();
            String ID = rs.getString(1);
            String NAME = rs.getString(2);
            String PASS = rs.getString(3);
            int ST = rs.getInt(4);
            user.setUserid(ID);
            user.setUsername(NAME);
            user.setPassword(PASS);
            user.setStatus(ST);
            userList.add(user);
        }
        /**提交时删除下列for循环*/
        for (User item : userList){
            System.out.println(item);
        }
        return userList;
    }

    public static void premenu() throws Exception{
        String choice;
        Scanner s=new Scanner(System.in);
        while(true){
            System.out.println("");
            System.out.println("---欢迎您使用蔬菜管理系统---");
            System.out.println("  **** 1.登录\t****");
            System.out.println("  **** 2.注册\t****");
            System.out.println("  **** 0.退出\t****");
            System.out.println("");
            System.out.println("请选择您的操作：");
            choice=s.next();
            switch(choice)
            {
                case "1":
                    System.out.println("欢迎您进行登录操作.....");
                    login();
                    break;
                case "2":
                    System.out.println("注册进行中.....");
                    register();
                    break;
                case "0":
                    System.out.println("谢谢使用，再见！");
                    return;
                default:
                    System.out.println("您的输入有误，请重新输入：");
                    break;
            }
        }
    }

    public static void login() throws Exception{
        Scanner sl = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String inputUsername = sl.next();
        if(UserController.isUsernameExists(inputUsername)){
            if(UserController.isStatusSuitable(inputUsername)==0){
                System.out.println("请输入密码：");
                String inputPassword = sl.next();
                if(UserController.isPasswordCorrect(inputUsername,inputPassword)){
                    System.out.println("欢迎您登录，"+inputUsername+"\n");
                    mainmenu(inputUsername);
                }
                else {
                    System.out.println("密码输入错误，请您重新登录...");
                }
            }
            else{
                System.out.println("该账号已经登录，请您重新登录...");
            }
        }
        else {
            System.out.println("该用户名不存在,请您重新登录...");
        }
    }

    public static boolean isUsernameExists(String username) throws Exception{
        List<User> userList = CreateList();
        for(User user1 : userList){
            if(user1.getUsername().equalsIgnoreCase(username)){
                return true;
            }
        }
        return false;
    }

    public static int isStatusSuitable(String username) throws Exception{
        List<User> userList = CreateList();
        for(User user1 : userList){
            if(user1.getUsername().equalsIgnoreCase(username)){
                return user1.getStatus();
            }
        }
        return 2;
    }

    public static boolean isPasswordCorrect(String username,String password) throws Exception{
        List<User> userList = CreateList();
        for(User user1 : userList){
            if(user1.getUsername().equalsIgnoreCase(username)){
                if(user1.getPassword().equals(password)){
                    Connection con = DBManager.getconn();
                    String sql = "update user set status = ? where username = ?";
                    PreparedStatement ps = con.prepareStatement(sql);
                    ps.setInt(1,1);
                    ps.setString(2,username);
                    ps.executeUpdate();
                    return true;
                }
            }
        }
        return false;
    }

    public static void register() throws Exception{
        Scanner sl = new Scanner(System.in);
        System.out.println("请输入自定义用户名：");
        String inputusername = sl.next();
        if(isUsernameExists(inputusername)){
            System.out.println("该用户名已存在，注册失败...");
        }
        else{
            System.out.println("请输入自定义密码：");
            String inputpassword = sl.next();
            int status = 0;
            addintodatabase(inputusername,inputpassword,status);
            System.out.println("注册成功，请登录获取服务...\n");
            login();
        }
    }

    public static void addintodatabase(String username,String password,int status) throws Exception{
        Connection conn = DBManager.getconn();
        String sql = "insert into user(username,password,status) values(?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,username);
        ps.setString(2,password);
        ps.setInt(3,status);
        ps.execute();
    }

    public static void mainmenu(String username) throws Exception{
        String choice;
        int flag = 0;
        Scanner sc = new Scanner(System.in);
        while (true){
            System.out.println("");
            System.out.println("---尊敬的"+username+",请选择您想要执行的功能模块---");
            System.out.println("  **** 1.用户管理模块\t****");
            System.out.println("  **** 2.蔬菜管理模块\t****");
            System.out.println("  **** 3.订单管理模块\t****");
            System.out.println("  **** 4.销量统计模块\t****");
            System.out.println("  **** 5.服务咨询模块\t****");
            System.out.println("  **** 0.退 出 程 序\t****");
            System.out.println("");
            System.out.println("请选择您的操作：");
            choice=sc.next();
            switch(choice)
            {
                case "1":
                    System.out.println("欢迎您访问用户管理模块.....\n");
                    flag = menu1(username,flag);
                    if(flag == 1){
                        return;
                    }
                    break;
                case "2":
                    System.out.println("欢迎您访问蔬菜管理模块.....\n");
                    menu2(username);
                    break;
                case "3":
                    System.out.println("欢迎您访问订单管理模块.....\n");
                    menu3(username);
                    break;
                case "4":
                    System.out.println("欢迎您访问销量统计模块.....\n");
                    menu4(username);
                    break;
                case "5":
                    System.out.println("欢迎您访问服务咨询模块.....\n");
                    menu5(username);
                    break;
                case "0":
                    System.out.println("感谢您的使用，再见！\n");
                    resetstatus(username);
                    return;
                default:
                    System.out.println("错误选项，请重新选择：");
                    break;
            }
        }
    }

    public static int menu1(String username,int flag) throws Exception {
        String choice;
        int num = 0;
        Scanner sc = new Scanner(System.in);
        while(true) {
            System.out.println("");
            System.out.println("---尊敬的"+username+",请选择您想要的操作---");
            System.out.println("  **** 1.保存我的信息\t****");
            System.out.println("  **** 2.密码安全存储\t****");
            System.out.println("  **** 3.查 询 信 息\t****");
            System.out.println("  **** 4.注 销 账 号\t****");
            System.out.println("  **** 0.退 出 模 块\t****");
            System.out.println("");
            System.out.println("请选择您的操作：");
            choice = sc.next();
            switch (choice) {
                case "1":
                    System.out.println("正在保存您的个人信息.....");
                    download(username);
                    break;
                case "2":
                    System.out.println("正在对您的密码进行加密处理.....");
                    num = coding(username);
                    break;
                case "3":
                    System.out.println("正在查询您的相关信息.....");
                    findinformation(username,num);
                    break;
                case "4":
                    System.out.println("***您确定要注销该账号吗？(Y/N)");
                    String inputChoice = sc.next();
                    if(inputChoice.equals("Y")){
                        deleteaccount(username);
                        flag = 1;
                        return flag;
                    }
                    else{
                        break;
                    }
                case "0":
                    System.out.println("正在退出该模块.....\n");
                    return 0;
                default:
                    System.out.println("您的输入有误，请重新输入：");
                    break;
            }
        }
    }

    public static void download(String username) throws Exception {
        String filename = "D:\\message.txt";
        User user = new User();
        List<User> list = CreateList();
        for(User userself : list){
            if(userself.getUsername().equals(username)){
                user.setUserid(userself.getUserid());
                user.setUsername(userself.getUsername());
                user.setPassword(userself.getPassword());
                user.setStatus(userself.getStatus());
            }
        }
        File file = new File(filename);
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(user);
        oos.close();
        fos.close();
        System.out.println("保存成功，文件地址为："+filename);
    }

    public static int coding(String username) throws Exception{
        List<User> userList = CreateList();
        User user1 = new User();
        for(User user : userList){
            if(user.getUsername().equals(username)){
                user1.setPassword(user.getPassword());
            }
        }
        System.out.println(user1.getPassword());
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入权值：(默认为非零)");
        int number = sc.nextInt();
        String result = addnumberintostring(user1.getPassword(),number);
        System.out.println("加密后的密码为："+result);
        Connection con = DBManager.getconn();
        String sql = "update user set password = ? where username = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1,result);
        ps.setString(2,username);
        ps.execute();
        return number;
    }

    public static String addnumberintostring(String password,int num){
        StringBuilder sb = new StringBuilder();
        for(char str : password.toCharArray()){
            char value = (char) ((str + num) % 128);
            sb.append(value);
        }
        return sb.toString();
    }

    public static void findinformation(String username,int num) throws Exception{
        List<User> userList = CreateList();
        User user1 = new User();
        for(User user : userList){
            if(user.getUsername().equals(username)){
                user1.setUserid(user.getUserid());
                user1.setUsername(user.getUsername());
                if(num==0){
                    user1.setPassword(user.getPassword());
                }
                else{
                    user1.setPassword(delnumfromstring(user.getPassword(),num));
                }
                user1.setStatus(user.getStatus());
            }
        }
        System.out.println("尊敬的"+username+",您的个人信息如下：");
        System.out.println(user1);
    }

    public static String delnumfromstring(String password,int num){
        StringBuilder sb = new StringBuilder();
        for(char str : password.toCharArray()){
            int v = str - num;
            if(v < 0){
                v = v + 128;
            }
            char value = (char)(v);
            sb.append(value);
        }
        return sb.toString();
    }

    public static void deleteaccount(String username) throws Exception{
        Connection con = DBManager.getconn();
        String sql = "delete from user where username = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1,username);
        ps.execute();
        System.out.println("已注销账号!");
    }

    /**以下为各位增加方法的部分*/
    public static void menu2(String username) throws Exception {
        String choice;
        Scanner sc = new Scanner(System.in);

    }

    public static void menu3(String username) throws Exception {
        String choice;
        Scanner sc = new Scanner(System.in);

    }

    public static void menu4(String username) throws Exception {
        String choice;
        Scanner sc = new Scanner(System.in);

    }

    public static void menu5(String username) throws Exception {
        String choice;
        Scanner sc = new Scanner(System.in);
    }
    /**到此处为止*/

    /**退出程序,将用户status改为0*/
    public static void resetstatus(String username) throws Exception{
        Connection con = DBManager.getconn();
        String sql = "update user set status = 0 where username = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1,username);
        ps.execute();
    }
}